<?php
header('Content-Type: text/html; charset=utf-8');
require_once dirname(__FILE__) . '/../../../incls/php/dbutils.class.php';
require_once dirname(__FILE__) . '/../../../incls/php/miscutils.class.php';
require_once dirname(__FILE__) . '/../../../incls/php/config.php';
require_once dirname(__FILE__) . '/../../../libs/phpMailer/class.phpmailer.php';
session_name(SESSION);
session_start();
$myPdo = DbUtils::createPdoInst();
$action = MiscUtils::getParam('action', '');
try {
  $myPdo->beginTransaction();
  switch ($action) {
    case 'register':
      register($myPdo);
      break;
    case 'login':
      login($myPdo);
      break;
    case 'send':
      send($myPdo);
      break;
    default:
      break;
  }
  $myPdo->commit();
} catch (PDOException $e) {
  echo $e->getMessage();
}

function register($myPdo) {
  unset($_SESSION['reg_user']);
  unset($_SESSION['reg_pass']);
  unset($_SESSION['reg_pass_re']);
  unset($_SESSION['reg_name']);
  unset($_SESSION['reg_name_last']);
  unset($_SESSION['reg_phone']);
  unset($_SESSION['reg_user_v']);
  unset($_SESSION['reg_pass_v']);
  unset($_SESSION['reg_pass_re_v']);
  unset($_SESSION['reg_name_v']);
  unset($_SESSION['reg_name_last_v']);
  unset($_SESSION['reg_phone_v']);
  $url = MiscUtils::getParam('url', '');
  $from = MiscUtils::getParam('from', '');
  $reg_user = MiscUtils::getParam('reg_user', '');
  $reg_pass = MiscUtils::getParam('reg_pass', '');
  $reg_pass_re = MiscUtils::getParam('reg_pass_re', '');
  $reg_name = MiscUtils::getParam('reg_name', '');
  $reg_name_last = MiscUtils::getParam('reg_name_last', '');
  $reg_phone = MiscUtils::getParam('reg_phone', '');
  
  $is_err = 0;
  if (!filter_var($reg_user, FILTER_VALIDATE_EMAIL)) {
    $_SESSION['reg_user'] = 'Not a proper email';
    $is_err = 1;
  } else {
    $cond_vals = new stdClass();
    $cond_vals->c = 't.account = :v1';
    $cond_vals->v = array(':v1' => $reg_user);
    $tmp = DbUtils::get($myPdo, TABLE_NAME_PREFIX_PLUGIN . 'ecom_customer', $cond_vals, NULL, NULL, NULL, NULL, NULL)->d;
    if (count($tmp) > 0) {
      $_SESSION['reg_user'] = 'Email has been used';
      $is_err = 1;
    }
  }
  if (strlen($reg_pass) < 6 || strlen($reg_pass) > 16) {
    $_SESSION['reg_pass'] = 'Password length must be 6 - 16 chars';
    $is_err = 1;
  }
  if ($reg_pass != $reg_pass_re) {
    $_SESSION['reg_pass_re'] = 'Confirm password is incorrect';
    $is_err = 1;
  }
  if ($reg_name == '') {
    $_SESSION['reg_name'] = 'Enter your first name';
    $is_err = 1;
  }
  if ($reg_name_last == '') {
    $_SESSION['reg_name_last'] = 'Enter your last name';
    $is_err = 1;
  }
  if ($reg_phone == '') {
    $_SESSION['reg_phone'] = 'Enter your phone number';
    $is_err = 1;
  }
  if ($is_err == 1) {
    $_SESSION['reg_user_v'] = $reg_user;
    $_SESSION['reg_pass_v'] = $reg_pass;
    $_SESSION['reg_pass_re_v'] = $reg_pass_re;
    $_SESSION['reg_name_v'] = $reg_name;
    $_SESSION['reg_name_last_v'] = $reg_name_last;
    $_SESSION['reg_phone_v'] = $reg_phone;
    echo "
    <script>
    parent.location.href = '$from';
    </script>
    ";
    return;
  }
  
  $obj = new stdClass();
  $obj->track_id = MiscUtils::unique();
  $obj->member_id = MEMBER_NORMAL_ID;
  $obj->account = $reg_user;
  $obj->password = md5($reg_pass);
  $obj->first_name = $reg_name;
  $obj->last_name = $reg_name_last;
  $obj->phone = $reg_phone;
  $obj->reg_date = date('Y-m-d', time());
  $obj->last_login = '0000-00-00';
  $obj->is_actived = 0;
  $obj->ip = _getIP();
  $obj->ip_place = '';
  DbUtils::add($myPdo, TABLE_NAME_PREFIX_PLUGIN . 'ecom_customer', $obj);
  $obj->id = $myPdo->lastInsertId();
  
  $profile = new stdClass();
  $tmp = DbUtils::get($myPdo, TABLE_NAME_PREFIX_PLUGIN . 'user_profile', NULL, NULL, NULL, NULL, NULL, NULL)->d;
  if (count($tmp) > 0) {
    $profile = $tmp[0];
  }
  try {
    $mailer = new PHPMailer();
    $mailer->IsSMTP();
    $mailer->Host = SMTP_HOST;
    $mailer->CharSet = "UTF-8";
    
    $content = '';
    
    $mailer->SMTPAuth = true;
    $mailer->Username = SMTP_USER_ATDN;
    $mailer->Password = SMTP_PASS_ATDN;
    $mailer->From = $profile->email;
    $mailer->FromName = $profile->shop_name;
    
    $mailer->Body = '<html><body>To activate your account <a href="http://' . URL . '?i=' . LOGIN_ID .'&script=active&t=' . $obj->track_id . '">click here</a></body></html>';
    $mailer->Subject = 'Activate Now';
  
    $mailer->isHTML(true);
    $mailer->AddAddress($obj->account, '');
    $mailer->Send();
    echo "
    <script>
    parent.location.href = '$url$reg_user';
    </script>
    ";
  } catch (phpmailerException $e) {
    echo $e->errorMessage(); //Pretty error messages from PHPMailer
  } catch (Exception $e) {
    echo $e->getMessage(); //Boring error messages from anything else!
  }
}

function login($myPdo) {
  unset($_SESSION['login_pass']);
  $url = MiscUtils::getParam('url', '');
  $from = MiscUtils::getParam('from', '');
  $login_user = MiscUtils::getParam('login_user', '');
  $login_pass = MiscUtils::getParam('login_pass', '');
  $_SESSION['login_user_v'] = $login_user;
  $cond_vals = new stdClass();
  $cond_vals->c = 't.account = :v1 AND t.password = :v2';
  $cond_vals->v = array(':v1' => $login_user, ':v2' => md5($login_pass));
  $opt = new stdClass();
  $opt->select_expr = 't.*, t1.title AS _member';
  $opt->join_expr = 'LEFT JOIN ' . TABLE_NAME_PREFIX_PLUGIN . 'ecom_customer_member AS t1 ON t1.id = t.member_id';
  $tmps = DbUtils::get($myPdo, TABLE_NAME_PREFIX_PLUGIN . 'ecom_customer', $cond_vals, NULL, NULL, NULL, NULL, $opt)->d;
  if (count($tmps) == 1) {
    $user = $tmps[0];
    if ($user->is_actived == 1) {
      $_SESSION['index' . USER] = $user;
      echo "
      <script>
      parent.location.href = '$url';
      </script>
      ";
    } else {
      $_SESSION['login_pass'] = 'The account is not activated';
      echo "
      <script>
      parent.location.href = '$from';
      </script>
      ";
    }
  } else {
    $_SESSION['login_pass'] = 'Login is incorrect';
    echo "
    <script>
    parent.location.href = '$from';
    </script>
    ";
  }
}

function send($myPdo) {
  unset($_SESSION['send_account']);
  $url = MiscUtils::getParam('url', '');
  $from = MiscUtils::getParam('from', '');
  $send_account = MiscUtils::getParam('send_account', '');
  $_SESSION['send_account_v'] = $send_account;
  $cond_vals = new stdClass();
  $cond_vals->c = 't.account = :v1';
  $cond_vals->v = array(':v1' => $send_account);
  $tmps = DbUtils::get($myPdo, TABLE_NAME_PREFIX_PLUGIN . 'ecom_customer', $cond_vals, NULL, NULL, NULL, NULL, NULL)->d;
  if (count($tmps) == 0) {
    $_SESSION['send_account'] = 'The account does not exist';
    echo "
    <script>
    parent.location.href = '$from';
    </script>
    ";
    return;
  }
  
  $profile = new stdClass();
  $tmp = DbUtils::get($myPdo, TABLE_NAME_PREFIX_PLUGIN . 'user_profile', NULL, NULL, NULL, NULL, NULL, NULL)->d;
  if (count($tmp) > 0) {
    $profile = $tmp[0];
  }
  try {
    $mailer = new PHPMailer();
    $mailer->IsSMTP();
    $mailer->Host = SMTP_HOST;
    $mailer->CharSet = "UTF-8";
    
    $content = '';
    
    $mailer->SMTPAuth = true;
    $mailer->Username = SMTP_USER_ATDN;
    $mailer->Password = SMTP_PASS_ATDN;
    $mailer->From = $profile->email;
    $mailer->FromName = $profile->shop_name;
    
    $key = new stdClass();
    $key->t = $tmps[0]->track_id;
    $key->s = time();
    
    $mailer->Body = '<html><body>To reset your password <a href="http://' . URL . '?i=' . LOGIN_ID .'&script=send&key=' . urlencode(MiscUtils::convert(json_encode($key), basename(dirname(__FILE__)))) . '">click here</a></body></html>';
    $mailer->Subject = 'Reset Password';
  
    $mailer->isHTML(true);
    $mailer->AddAddress($send_account, '');
    $mailer->Send();
    if (isset($_SESSION['login_user_v'])) {
      unset($_SESSION['login_user_v']);
    }
    if (isset($_SESSION['login_pass'])) {
      unset($_SESSION['login_pass']);
    }
    echo "
    <script>
    parent.location.href = '$url';
    </script>
    ";
  } catch (phpmailerException $e) {
    echo $e->errorMessage(); //Pretty error messages from PHPMailer
  } catch (Exception $e) {
    echo $e->getMessage(); //Boring error messages from anything else!
  }
}

function _getIP(){ 
  if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) {
    $ip = getenv("HTTP_CLIENT_IP"); 
  } else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) {
    $ip = getenv("HTTP_X_FORWARDED_FOR"); 
  } else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) {
    $ip = getenv("REMOTE_ADDR"); 
  } else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) {
    $ip = $_SERVER['REMOTE_ADDR']; 
  } else {
    $ip = "unknown"; 
  }
  return($ip);
}
?>
